package com.zuipin.controller;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zuipin.entity.DrawRecord;
import com.zuipin.framework.annotation.Valid;
import com.zuipin.framework.annotation.Valids;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.result.Result;
import com.zuipin.service.IDrawRecordService;
import com.zuipin.util.DateUtils;
import com.zuipin.util.WechatUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @description :
 * @author : xujinding
 * @date : 2017年3月24日 下午1:48:19
 */
@Api(value = "提现-xujinding", description = "提现-xujinding")
@Controller
@RequestMapping(value = "/withdraw")
public class DrawRecordController {
	@Value("${ipAddress}")
	private String				ipAddress;
	
	private Logger				log	= Logger.getLogger(DrawRecordController.class);
	@Resource
	private IDrawRecordService	drawRecordService;
	
	@Valids({ @Valid(name = "drawRecord.money", required = true, minValue = 1),
			@Valid(name = "drawRecord.remark", required = true, maxLength = 100, minLength = 1),
			@Valid(name = "drawRecord.drawNo", required = true),
			@Valid(name = "drawRecord.openId", required = true),
			@Valid(name = "drawRecord.mchid", required = true),
			@Valid(name = "drawRecord.custName", required = true),
			@Valid(name = "drawRecord.payKey", required = true),
			@Valid(name = "drawRecord.sysId", required = true),
			@Valid(name = "drawRecord.ipAddress", required = true),
			@Valid(name = "drawRecord.appid", required = true) })
	@ResponseBody
	@RequestMapping(value = "/drawMoney", method = RequestMethod.POST)
	@ApiOperation(notes = "提现（当出现非数字，汉字，字母用“_替换”）", value = "提现（当出现非数字，汉字，字母用“_替换”）")
	public Result drawMoney(@RequestBody DrawRecord drawRecord) {
		Result result = new Result();
		short isSuccess = DrawRecord.NO;
		String exceptionStr = "";
		String reg = "^[a-zA-Z0-9_\u4e00-\u9fa5]+$";
		drawRecord.setRemark(filterStr(drawRecord.getRemark(), reg, "_"));
		drawRecord.setCustName(filterStr(drawRecord.getCustName(), reg, "_"));
		//drawRecord.setRemark("提现了" + drawRecord.getMoney() + "元");
		try {
			JSONObject jobj = WechatUtil.callTransfers(drawRecord.getAppid(), drawRecord.getMchid(),
					drawRecord.getPayKey(), drawRecord.getMoney().doubleValue(),
					drawRecord.getDrawNo(), WechatUtil.CHECK_OPTION_NO, drawRecord.getCustName(),
					drawRecord.getOpenId(), ipAddress, drawRecord.getRemark());
			isSuccess = DrawRecord.YES;
			exceptionStr = jobj.toString();
		} catch (Exception e) {
			log.error("提现失败：：", e);
			exceptionStr = e.getMessage();
		}
		drawRecord.setDelFlag(DrawRecord.NO);
		drawRecord.setCreateTime(DateUtils.getCurrentDateTime());
		drawRecord.setUpdateTime(DateUtils.getCurrentDateTime());
		drawRecord.setIsSuccess(isSuccess);
		//截取一部分保存到数据库
		if (exceptionStr.length() > 1000) {
			exceptionStr = exceptionStr.substring(0, 990);
		}
		drawRecord.setReturnValue(exceptionStr);
		drawRecordService.saveDrawRecord(drawRecord);
		if (DrawRecord.YES == isSuccess) {
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(drawRecord);
		} else {
			result.setErrorCode(ErrorCode.DRAW_FAIL);
			result.setData(drawRecord);
			result.setMessage("draw fail");
		}
		return result;
	}
	
	/**
	 * 根据正则将源字符串  用replace替换
	 * @param str  源字符串
	 * @param reg  正则
	 * @param replace  替换
	 * @return
	 */
	public String filterStr(String str, String reg, String replace) {
		//String reg = "";
		StringBuffer remarkBuff = new StringBuffer();
		if (str != null && str.length() > 0) {
			for (int i = 0; i < str.length(); i++) {
				String temp = str.charAt(i) + "";
				Pattern p = Pattern.compile(reg);
				Matcher m = p.matcher(temp);
				if (m.matches()) {
					remarkBuff.append(temp);
				} else {
					remarkBuff.append(replace);
				}
			}
		} else {
			remarkBuff.append(replace);
		}
		return remarkBuff.toString();
		
	}
	
}
